﻿using System.Configuration;
using System.Net.Mail;
using System.Text;

namespace TWA.TFS
{
    /// <summary>
    /// Tools for preparing and sending email.
    /// </summary>
    internal static class Email
    {
        internal static MailMessage CreateMessage (MailAddressCollection toAddresses, MailAddress replyToAddress, string subject, string body)
        {
            var message = new MailMessage ();

            string fromAddress = ConfigurationManager.AppSettings ["MailAddressFrom"];
            string fromDisplayName = ConfigurationManager.AppSettings ["MailFromDisplayName"];
            message.From = new MailAddress (fromAddress, fromDisplayName);
            
            message.ReplyTo = replyToAddress;
            message.To.Add (toAddresses.ToString ());
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.BodyEncoding = Encoding.UTF8;
            message.Body = body;

            return message;
        }

        internal static void SendMessage (MailMessage message)
        {
            var smtp = new SmtpClient (ConfigurationManager.AppSettings ["SMTPServer"]);

            if (!string.IsNullOrEmpty (ConfigurationManager.AppSettings ["SMTPPassword"]))
            {
                smtp.Credentials = new System.Net.NetworkCredential (
                    ConfigurationManager.AppSettings ["SMTPUser"],
                    ConfigurationManager.AppSettings ["SMTPPassword"]);
            }

            Logger.Log ("Sending mail..");
            smtp.Send (message);
            Logger.Log ("Email sent.");
        }
    }
}